package com.ywjt.platformbusiness.store.order.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EdgeEffect;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.ywjt.platformbusiness.R;
import com.ywjt.platformbusiness.base.BaseActivity;
import com.ywjt.platformbusiness.base.BaseVPFragment;
import com.ywjt.platformbusiness.common.UserData;
import com.ywjt.platformbusiness.constants.Constants;
import com.ywjt.platformbusiness.constants.UrlConstants;
import com.ywjt.platformbusiness.http.HttpRequest;
import com.ywjt.platformbusiness.http.HttpStringCallBack;
import com.ywjt.platformbusiness.store.activity.SortingCenterActivity;
import com.ywjt.platformbusiness.store.adapter.StoreOrderListAdapter;
import com.ywjt.platformbusiness.store.order.model.StoreOrderListModel;
import com.ywjt.platformbusiness.util.JsonUtils;
import com.ywjt.platformbusiness.util.SoftKeyboardUtils;
import com.ywjt.platformbusiness.widget.CenterDialogEdit;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class ActivityOrderSearch extends BaseActivity implements View.OnClickListener {
    private StoreOrderListAdapter adapter;
    private RecyclerView rcView;
    private List<StoreOrderListModel.ResultDTO.RecordsDTO> data;
    private LinearLayout llNodata;

    private int currentPage=1;
    private SmartRefreshLayout refresh;
    private EditText etContent;
    private int count=0;
    private int status=0;
    private int posi=0;
    private String orderNumber="";


    public static void actionStart(Context context) {
        Intent intent = new Intent(context, ActivityOrderSearch.class);
        context.startActivity(intent);
    }

    //获取数据
    public void getData(){
        JSONObject map = new JSONObject();
        try {
            map.put("pageNo",currentPage);
            map.put("pageSize", Constants.PAGESIZE);
            map.put("shopId", UserData.create(ActivityOrderSearch.this).get(UserData.MERCHANTID));
            if (!orderNumber.equals("")){
                map.put("orderNumber",orderNumber);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(ActivityOrderSearch.this).doPost(UrlConstants.merchant_getOrderByCode, null, map, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {
                String datas = result.toString();
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(datas);
                    String message = jsonObject.getString("message");
                    Boolean success = jsonObject.getBoolean("success");
                    if (success) {
                        refresh.finishRefresh();
                        Object obj = JsonUtils.fromJson(result.toString(), StoreOrderListModel.class);
                        if (obj instanceof StoreOrderListModel) {
                            StoreOrderListModel model=(StoreOrderListModel)obj;
                            if (currentPage == 1) {
                                data.clear();
                                count = model.getResult().getTotal();
                                if (model.getResult().getRecords().size() > 0) {
                                    data=model.getResult().getRecords();
                                    llNodata.setVisibility(View.GONE);
                                    rcView.setVisibility(View.VISIBLE);
                                    adapter=new StoreOrderListAdapter(data,status);
                                    rcView.setLayoutManager(new LinearLayoutManager(ActivityOrderSearch.this));
                                    rcView.setAdapter(adapter);
                                    if (adapter.getItemCount() < count) {
                                        //还有多的数据
                                        refresh.finishRefresh();
                                    } else {
                                        //没有更多数据（上拉加载功能将显示没有更多数据）
                                        refresh.finishRefreshWithNoMoreData();
                                    }
                            adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
                                @Override
                                public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                                                switch (data.get(position).getStatus()){
                                                    //case 3:
                                                        //已经取消
                                                      //  ActivityOrderCanceled.actionStart(context,data.get(position).getOrderNum());
                                                     //   break;
                                                    case 0:
                                                        StoreOrderUnPay.actionStart(ActivityOrderSearch.this,data.get(position));
                                                        break;
                                                    case 1:
                                                        StoreOrderUnSend.actionStart(ActivityOrderSearch.this,data.get(position));
                                                        break;
                                                    case 2:
                                                        StoreOrderUnConfirm.actionStart(ActivityOrderSearch.this,data.get(position));
                                                        break;
                                                    case 3:
                                                        StoreOrderFinish.actionStart(ActivityOrderSearch.this,data.get(position));
                                                        break;
                                                    case -2:
                                                        StoreOrderPostSale.actionStart(ActivityOrderSearch.this,data.get(position));
                                                        break;
                                                    default:

                                                        break;
                                                }

                                }
                            });
                                adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                                    @Override
                                    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                                        posi=position;
                                        switch (view.getId()){

//                                            case R.id.tvCancle:
//                                                //取消订单
//                                                ReasonPickBottomDialog dialog1=new ReasonPickBottomDialog(context,1,"取消订单",2);
//                                                dialog1.show(getFragmentManager());
//                                                break;
                                      //      case R.id.tvGotoPay:
                                                //去支付
                                                //Activity_Pay_Order.actionStart(context,String.valueOf(data.get(posi).getOrderNum()),data.get(posi).getRealPrice().doubleValue(),"");
                                    //            break;
                                 //               case R.id.tvConfirm:
                                                //确认收货
                                               // confirmReceipt(position);
                                  //              break;
//                                            case R.id.tvCheckTrace:
//                                            case R.id.tvCheckTraceReturn:
                                                //查看物流
//                                                ActivityGoodsTrack.actionStart(context,model.getData().get(position).getExpressCode(),
//                                                        model.getData().get(position).getExpressNum(),
//                                                        model.getData().get(position).getOrderDetailList().get(0).getGoodsCover(),
//                                                        model.getData().get(position).getOrderDetailList().size());
                                               // break;
                                            case R.id.tvTipSendGoods:
                                               //去发货
                                                SortingCenterActivity.actionStart(ActivityOrderSearch.this,data.get(position),"1");
                                                break;
                                            case R.id.tvPriceModify:
                                                //修改价格
                                                CenterDialogEdit edit=new CenterDialogEdit(ActivityOrderSearch.this,"修改价格",
                                                        data.get(position).getActuallyMoney()+"");
                                                edit.setClicklistener(new CenterDialogEdit.ClickListenerInterface() {
                                                    @Override
                                                    public void confirm(String price) {
                                                        edit.dismiss();
                                                        updatePrice(data.get(position).getId(),price);
                                                    }
                                                });
                                                edit.show();
                                                break;
                                        }
                                    }
                                });
                                } else {
                                    refresh.finishRefreshWithNoMoreData();
                                    llNodata.setVisibility(View.VISIBLE);
                                    rcView.setVisibility(View.GONE);
                                }
                            }else {
                                data.addAll(model.getResult().getRecords());
                                adapter.notifyDataSetChanged();
                                if (adapter.getItemCount() < count) {
                                    //还有多的数据
                                    refresh.finishRefresh();
                                } else {
                                    //没有更多数据（上拉加载功能将显示没有更多数据）
                                    refresh.finishRefreshWithNoMoreData();
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
                refresh.finishLoadMore();
                refresh.finishRefresh();
            }
        });
    }


    //修改价格
    public void updatePrice(String id,String price){
        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("id",id);
            jsonObject.put("actuallyMoney",price);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        new HttpRequest(getContext()).doPost(UrlConstants.merchant_modifyOrderPrice, "",jsonObject, new HttpStringCallBack() {
            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onSuccess(Object result) {

                String data = result.toString();
                //把请求得数据转换成json对象
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject(data);
                    String message = jsonObject.getString("message");
                    Boolean success=jsonObject.getBoolean("success");
                    if(success){
                        getData();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }


    @Override
    protected void init(Bundle savedInstanceState) {

    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_order_search;
    }

    public void initView(){
        setTitleText("订单搜索");
        refresh=findViewById(R.id.refresh);
        rcView=findViewById(R.id.rcCommon);
        llNodata=findViewById(R.id.llNodata);
        etContent=findViewById(R.id.etContent);
        etContent.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                orderNumber=s.toString().trim();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        etContent.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                    SoftKeyboardUtils.hideSoftKeyboard2(ActivityOrderSearch.this);
                    getData();
                }
                return false;
            }
        });
        data=new ArrayList<>();
        getData();
    }

    @Override
    protected void initData() {

    }

    /**
     * 获取要使用的标题栏样式(此函数由子类重写)
     *
     * @return
     */
    @Override
    protected int getTitleBarType() {
        return 0;
    }


    public void setView(){
        data=new ArrayList<>();
        refresh.setEnableAutoLoadMore(true);//开启自动加载功能（非必须）
        refresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage = 1;
                        getData();
                    }
                }, 1000);
            }
        });
        refresh.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        currentPage++;
                        getData();
                    }
                }, 1000);
            }
        });
    }

    @Override
    public void onClick(View v) {

    }
}
